import Config from '@/common/js/config.js';

function apiRoute(p_uri, p_body, p_method) {
    var obj = {};
    obj.uri = p_uri;
    obj.method = p_method || 'GET';
    obj.body = p_body;
    return obj;
}

function formatTime(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();

    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();


    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')

    function formatNumber(n) {
        n = n.toString();
        return n[1] ? n : '0' + n
    }
}

var timer;

function setPageData(page, elmt) {
    clearTimeout(timer);
    var key = elmt.target.dataset.key;
    var obj = {};
    obj[key] = elmt.detail.value;
    timer = setTimeout(function () {
        page.setData(obj);
    }, 200);

    return obj;
}

function isObject(o) {
    return Object.prototype.toString.call(o) === '[object Object]';
}

function extend(target, source, deep) {
    target = target || {};
    var sType = typeof source,
        i = 1,
        options;
    if (sType === 'undefined' || sType === 'boolean') {
        deep = sType === 'boolean' ? source : false;
        source = target;
        target = this;
    }
    if (typeof source !== 'object' && Object.prototype.toString.call(source) !== '[object Function]')
        source = {};
    while (i <= 2) {
        options = i === 1 ? target : source;
        if (options != null) {
            for (var name in options) {
                var src = target[name],
                    copy = options[name];
                if (target === copy)
                    continue;
                if (deep && copy && typeof copy === 'object' && !copy.nodeType)
                    target[name] = extend(src ||
                        (copy.length != null ? [] : {}), copy, deep);
                else if (copy !== undefined)
                    target[name] = copy;
            }
        }
        i++;
    }
    return target;
}

function navigateTo(url) {
    uni.navigateTo({
        url: url
    });
}

function redirectTo(url) {
    uni.redirectTo({
        url: url
    });
}

function back(pageCount) {
    pageCount = pageCount || 1;
    uni.navigateBack({
        delta: pageCount
    })
}

function alert(msg) {
    var msg = isObject(msg) ? msg.msg : msg;
    uni.showModal({
        title: '提示',
        content: msg,
        showCancel: false
    });
}

function toast(msg) {
    uni.showToast({
        title: msg,
        icon: 'none',
        duration: 3000
    });
}

function confirm(content, yesFunc, noFunc, buttonArr) {
    uni.showModal({
        title: '提示',
        content: content,
        confirmText: buttonArr ? buttonArr[0] : '是',
        cancelText: buttonArr ? buttonArr[1] : '否',
        success: function (res) {
            console.log(res);
            if (res.confirm) {
                if (typeof yesFunc == 'function') {
                    yesFunc();
                }
            } else {
                if (typeof noFunc == 'function') {
                    noFunc();
                }
            }
        }
    });
}

function showLoading(msg) {
    msg = msg || '加载中...';
    if (uni.showLoading) {
        uni.showLoading({
            title: msg,
            mask: true
        });
    } else {
        toast(msg);
    }
}

function hideLoading() {
    if (uni.hideLoading) {
        uni.hideLoading();
    }
}

function setStorage(key, value, times) {
    if (times) {
        value = {
            myOutDate: new Date().getTime() + 1000 * 60 * times,
            data: value
        };
    }
    uni.setStorageSync(key, value);

}

function getStorage(key, chkTimes) {
    let cData = uni.getStorageSync(key);
    if (!cData) {
        return null;
    }
    if (cData && chkTimes) {
        if (cData.myOutDate > new Date().getTime()) {
            return cData.data;
        } else {
            return null;
        }
    } else {
        if (cData.myOutDate) {
            return cData.data;
        } else {
            return cData;
        }
    }
}

function removeStorage(key) {
    uni.removeStorageSync(key);
}

function ajax(p_route, p_option) {
    let def = {
        url: Config.host + p_route.uri,
        header: {
            'content-type': 'application/json'
        },
        data: p_route.body,
        method: p_route.method,
        showLoading: true,
        loadingContent: '数据加载中',
        cacheKey: null,
        cacheTime: 0,
        beforeSend: null,
        myComplete: null
    };

    let loginUser = getLoginUser();
    if (loginUser) {
        def.header.loginusertoken = loginUser.token;
    }
    if (p_option) {
        extend(def, p_option, true);
    }

    return new Promise((resolve, reject) => {
        if (def.cacheKey && def.cacheTime) {
            var cData = getStorage(def.cacheKey, true);
            if (cData) {
                return resolve(cData);
            }
        }

        def.beforeSend = (() => {
            if (typeof def.myBeforeSend === 'function') {
                if (!def.myBeforeSend()) {
                    return;
                }
            }

            if (def.showLoading) {
                showLoading(def.loadingContent);
            }
        });


        def.fail = ((xhr, errorType, err) => {
            if (xhr.response) {
                try {
                    var errObj = JSON.parse(xhr.response);
                    alert(errObj.msg);
                } catch (ex) {
                    alert(xhr.response);
                }
                console.log(xhr.response);
            } else {
                console.log(xhr.message ? xhr.message : xhr.response.data);
            }

            reject(xhr.response);
        });

        def.complete = (d) => {
            if (typeof def.myComplete === 'function') {
                def.myComplete(d);
            }
            hideLoading();
        };

        def.success = function (res) {
            var d = res.data; // 不同ajax框架可能返回值不一样，这里多一步，最个转换
            if (d.success) {
                if (def.cacheKey && def.cacheTime) {
                    setStorage(def.cacheKey, d, def.cacheTime);
                }
                resolve(d)
            } else {
                alert(d);
                console.log(d);
                reject(d);
            }
        };

        def.beforeSend();
        uni.request(def);
    })


}

function getLoginUser() {
    let userInfo = getStorage('loginUser');
    return userInfo;
}

function setLoginUser(userInfo) {
    setStorage('loginUser', userInfo);
}

function loginOut() {
    uni.clearStorageSync();
    setLoginUser(null);
}

module.exports = {
    apiRoute,
    formatTime,
    setPageData,
    extend,
    setStorage,
    getStorage,
    removeStorage,
    ajax,
    alert,
    toast,
    confirm,
    showLoading,
    hideLoading,
    redirectTo,
    navigateTo,
    back,
    getLoginUser,
    setLoginUser,
    loginOut
};
